package com.ht.module.bus.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ht.abnormal.HtException;
import com.ht.module.bus.entity.BusResource;
import com.ht.module.bus.mapper.BusResourceMapper;
import com.ht.module.bus.service.IBusResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.module.common.service.ICommonService;
import com.ht.util.CommMethod;
import com.ht.util.FileUtil;
import com.ht.util.Pager;
import com.ht.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;

/**
 * <p>
 * 资源表 服务实现类
 * </p>
 *
 * @author hejialun
 * @since 2021-08-11
 */
@Service
public class BusResourceServiceImpl extends ServiceImpl<BusResourceMapper, BusResource> implements IBusResourceService {
    @Value("${upload_resource_max_size}")
    public long UPLOAD_RESOURCE_MAX_SIZE;
    @Autowired
    private ICommonService iCommonService;



    @Override
    public Pager<BusResource> findPageByMe(Pager<BusResource> pager, BusResource en) {
        QueryWrapper<BusResource> qw=new QueryWrapper<>();
        if(StrUtil.isNotEmpty(en.getName())){
            qw.like("tab.name",en.getName());
        }
        if(StrUtil.isNotEmpty(en.getType())){
            qw.eq("tab.type",en.getType());
        }
        qw.eq("tab.create_user",UserUtil.getUserId());
        return baseMapper.findPage(pager,qw);
    }



    @Override
    public void add(BusResource busResource) throws IOException {
        //判断是否上传了文件
        if(ObjectUtil.isEmpty(busResource.getFile())){
            throw new HtException("请选择需要上传的资源！");
        }
        //文件大小判断
        if(busResource.getFile().getSize()>UPLOAD_RESOURCE_MAX_SIZE){
            throw new HtException("上传文件过大！当前系统资源限制最大值："+ FileUtil.getFileSize(UPLOAD_RESOURCE_MAX_SIZE,"M")+"m");
        }
        //插入一条数据
        busResource.setPath(iCommonService.uploadFile(busResource.getFile()));
        CommMethod.beanCreate(busResource);
        baseMapper.insert(busResource);
    }

    @Override
    @Transactional
    public void delById(String id) {
        //查询出当前资源
        BusResource busResource=baseMapper.selectById(id);
        //判断是否是当前登录人创建的
        if(!busResource.getCreateUser().equals(UserUtil.getUserId())){
            throw new HtException("没有权限删除当前资源！");
        }
        //删除文件
        iCommonService.delFile(busResource.getPath());
        //删除库表数据
        baseMapper.deleteById(id);
    }



}
